package com.bw.controller.task;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.controller.order.PiOrderController;
import com.bw.entity.alipay.PiPayLog;
import com.bw.entity.order.PiOrder;
import com.bw.entity.order.PiOrderLog;
import com.bw.service.alipay.IPiPayLogService;
import com.bw.service.dc.IPiLinkmanService;
import com.bw.service.order.IPiOrderLogService;
import com.bw.service.order.IPiOrderService;
import com.bw.utils.alipay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

/**
 * 定时类
 */
@Component
public class OrderSche {
    @Autowired
    private IPiOrderService iPiOrderService;
    @Autowired
    private IPiLinkmanService iPiLinkmanService;
    @Autowired
    private IPiOrderLogService orderLogService;//订单操作记录
    @Autowired
    private IPiPayLogService payLogService;
    //定义日志工具
    private final Logger log = LoggerFactory.getLogger(OrderSche.class);
    //每隔30分钟执行一次
    @Scheduled(cron = "0 0/30 * * * ?")//定时扫描，并关闭订单
    public void closeOrder(){
        try {
            log.info("查询未支付订单");
            //查询未支付订单
            QueryWrapper Wrapper  = new QueryWrapper();
            Wrapper .eq("state", 3);
            List<PiOrder> list = iPiOrderService.list(Wrapper);//查询list
            log.info("开始对比编号");
            for (PiOrder order: list) {
                //商户订单号
                String out_trade_no = order.getCode();
                //获得初始化的AlipayClient
                AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
                //设置请求参数
                AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
                alipayRequest.setReturnUrl(AlipayConfig.return_url);
                alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

                //支付宝交易号
                String trade_no="";
                alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                        + "\"trade_no\":\""+ trade_no );
                //---日志记录用数据
                //支付状态
                String state = alipayClient.execute(alipayRequest).getCode();//*****************
                //价格
                String totalAmount = alipayClient.execute(alipayRequest).getTotalAmount();
                //支付端流水号
                String tradeNo = alipayClient.execute(alipayRequest).getTradeNo();
                //----------
                PiPayLog payLog = new PiPayLog();
                //判断状态
                log.info("判断状态");
                if(state.equals("1000")){
                    log.info("订单已支付");
                    order.setState(4);
                    iPiOrderService.saveOrUpdate(order);//保存
                    //添加操作日志
                    PiOrderLog log = new PiOrderLog();
                    log.setOrderId(order.getId());
                    log.setUserName("admin");
                    log.setRemarks("订单已支付成功");
                    log.setCreatetime(new Date());
                    orderLogService.save(log);
                    //支付日志添加
                    payLog.setOutTradeNo(out_trade_no);
                    payLog.setCreateTime(new Date());
                    payLog.setTotalAmount(new BigDecimal(totalAmount));
                    payLog.setUserId(order.getUserid());
                    payLog.setTradeNo(tradeNo);
                    payLog.setPayType("系统扫单...");
                    payLog.setTradeState("订单已支付");
                    payLogService.save(payLog);
                } else{
                    //30分钟没支付关闭订单
                    //获取当前时间和前一次操作的订单日志比较
                    log.info("获取订单修改日期对比"+order.getCode());
                    Long old = order.getUpdateDate().getTime();
                    Long now = new Date().getTime();
                    Long ck = (now-old)/60*1000;
                    //对比时间，若超过30，则关闭
                    log.info("订单未支付对比时间");
                    if(ck>30) {
                        order.setState(6);
                        iPiOrderService.saveOrUpdate(order);//保存
                        //添加操作日志
                        PiOrderLog log = new PiOrderLog();
                        log.setOrderId(order.getId());
                        log.setTbId(new Long(1));
                        log.setUserName("admin");
                        log.setRemarks("订单支付超时，已关闭");
                        log.setCreatetime(new Date());
                        orderLogService.save(log);
                        //支付超时日志添加
                        payLog.setOutTradeNo(out_trade_no);
                        payLog.setCreateTime(new Date());
                        payLog.setTotalAmount(new BigDecimal(totalAmount));
                        payLog.setUserId(order.getUserid());
                        payLog.setTradeNo(tradeNo);
                        payLog.setPayType("系统扫单....");
                        payLog.setTradeState("支付超时订单已关闭");
                        payLogService.save(payLog);
                    }
                    log.info("关闭支付超时订单");
                }
            }
        } catch (Exception e) {
            log.error("扫单失败，{}"+e.toString());
        }
    }
}
